package com.example.pcl.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.pcl.constant.JwtClaimsConstant;
import com.example.pcl.constant.MessageConstants;
import com.example.pcl.exception.ObjectException;
import com.example.pcl.mapper.AdminMapper;
import com.example.pcl.pojo.dto.AdminLoginDto;
import com.example.pcl.pojo.entity.Admin;
import com.example.pcl.properties.JwtProperties;
import com.example.pcl.service.IAdminService;
import com.example.pcl.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author xx
 * @since 2024-12-17
 */
@Service
@RequiredArgsConstructor
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    private final JwtProperties jwtProperties;

    /**
     * 管理员登录
     *
     * @param loginDto dto
     * @return token
     */
    @Override
    public String login(@NotNull AdminLoginDto loginDto) {
        Admin admin = getOne(new LambdaQueryWrapper<Admin>()
                .eq(Admin::getUsername, loginDto.getUsername()));
        //用户不存在
        if (admin == null) {
            throw new ObjectException(MessageConstants.ADMIN_ERR);
        }
        String password = DigestUtil.md5Hex(loginDto.getPassword().getBytes());
        //密码不正确
        if (!admin.getPassword().equals(password)) {
            throw new ObjectException(MessageConstants.ADMIN_PASSWORD_ERR);
        }
        //账号被禁用
        if (admin.getStatus().equals(Admin.DISABLE)) {
            throw new ObjectException(MessageConstants.ACCOUNT_LOCKED);
        }
        //生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, admin.getAdminId());
        return JwtUtil.createJwt(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), claims);
    }
}
